package itsm.isperp.module.controller.api.wechat;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.service.UploadFileService;
import itsm.isperp.framework.utils.DateUtils;
import itsm.isperp.framework.utils.FileUploadUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.ImageUtils;
import itsm.isperp.framework.web.paging.RenderPager;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppUploadFile;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.serviceCatalog.SrcService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUploadFileService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.module.service.slm.SlmServiceTargetService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jdbc.support.DatabaseType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-3-15
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/wechat/incident")
public class WechatIncidentController {

  @Autowired
  IcdIncidentService icdIncidentService;

  @RequestMapping("newIncident")
  public ModelAndView newIncident(String openid, HttpServletRequest httpreq,
      RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException {

    if (StringUtils.isEmpty(openid)) {
    }

    String timestamp = httpreq.getParameter("timestamp");
    String nonceStr = httpreq.getParameter("nonceStr");
    String signature = httpreq.getParameter("signature");

    ModelAndView mv = new ModelAndView("api/wechat/incident/newIncident");
    SrcServiceService srcServiceService = ContextHolder
        .getSpringBean(SrcServiceService.class);
    JqGridRequest req = new JqGridRequest();
    req.isPageable(false);
    req.setSelectColumns("id", "name");
    List<SrcService> list = srcServiceService.findAll(req);

    mv.addObject("timestamp", timestamp);
    mv.addObject("nonceStr", nonceStr);
    mv.addObject("signature", signature);

    mv.addObject("id", HibernateUUIDGenerator.generate());
    mv.addObject("services", list);
    mv.addObject("openid", openid);

    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    AppUser appUser = appUserService.findByOpenid(openid, "id", "name",
        "enable", "mobile", "fullname", "email", "tel","address");
    if (appUser == null)
      return null;

    /*if (!appUser.isEnable()) {
      mv.addObject("error", "用户未通过认证，请联系管理员！");
      mv.addObject("success", 1);
      mv.addObject("openid", openid);
      mv.setViewName("api/wechat/setting/registerNotice");
      return mv;
    }*/

    String ciCode = httpreq.getParameter("ciCode");
    int ciSize = 0;
    List<Map<String, Object>> userCis = null;
    ConfCiService confCiService = ContextHolder.getSpringBean("confCiService");
    JqGridRequest ciReq = new JqGridRequest();
    ciReq.isPageable(false);
    if (StringUtils.isEmpty(ciCode)) {
      userCis = confCiService.findDetailByCusUserId(appUser.getId(), ciReq);

    } else {

      ciReq.setSearchString(" a.code ='" + ciCode + "' OR  a.asset_code='"
          + ciCode + "' ");

      userCis = confCiService.findAllDetailByRequest(ciReq);
    }
    ciSize = userCis.size();

    mv.addObject("userCis", userCis);
    mv.addObject("ciSize", ciSize);
    Map<String, Object> mp = appUserService.findOneDetailByUsername(appUser
        .getName());
    String userDepartmentName = (String) mp
        .get("department_treenode_name_path");
    mv.addObject("appUser", appUser);
    mv.addObject("userDepartmentName", userDepartmentName);
    AppDictService appDictService = ContextHolder
        .getSpringBean(AppDictService.class);
    List<AppDict> incidentType=appDictService.findByType("INCIDENT_TYPE");
    mv.addObject("incidentType", incidentType);
    return mv;
  }

  /**
   * 保存事件单
   * 
   * @param request
   * @param redirectAttributes
   * @return
   * @throws SQLException
   */
  @RequestMapping("save")
  public String save(HttpServletRequest request,
      RedirectAttributes redirectAttributes) throws SQLException {

    String id = request.getParameter("id");
    String openid = request.getParameter("openid");
    String tel = request.getParameter("tel");
    String mobileShort = request.getParameter("mobileShort");
    String email = request.getParameter("Email");
    String mobile = request.getParameter("mobile");
    String tciId = request.getParameter("ciId");
    String otherCI = request.getParameter("otherCi");
    String addressDetail = request.getParameter("address");
    String incidentType = request.getParameter("incidentType");

    String cusUserId = null;
    AppUserService appUserService = ContextHolder
        .getSpringBean(AppUserService.class);
    IcdIncident entity = new IcdIncident();
    AppUser cusUser = appUserService.findByOpenid(openid, "id", "name",
        "fullname");

    // 更新电话
    Set<String> columns = new HashSet<>();
    if (!StringUtils.isWhitespace(mobileShort)) {

      columns.add("mobile_short");
    }
    if (!StringUtils.isWhitespace(email)) {
      cusUser.setEmail(email);
      columns.add("email");
    }
    if (!StringUtils.isWhitespace(mobile)) {
      cusUser.setMobile(mobile);
      columns.add("mobile");
    }
    if (!StringUtils.isWhitespace(tel)) {
      cusUser.setTel(tel);
      columns.add("tel");
    }
    if(!StringUtils.isWhitespace(addressDetail))
    {
      cusUser.setAddress(addressDetail);
      columns.add("address");
    }

    appUserService.dynamicUpdateSpecific(cusUser, columns);

    if (cusUser != null) {
      cusUserId = cusUser.getId();

      // 设置一个默认的项目
      List<Map<String, Object>> projects = appUserService
          .findUserProjects(cusUserId);
      if (projects != null && !projects.isEmpty()) {
        entity.setProjectId(projects.get(0).get("id").toString());
      }
    }

    redirectAttributes.addAttribute("id", id);
    redirectAttributes.addAttribute("success", "1");
    redirectAttributes.addAttribute("openid", openid);
    redirectAttributes.addAttribute("cusUserId", cusUserId);

    if (this.icdIncidentService.exists(id)) {
      return "redirect:myIncident";
    }
    String ciId = "";
    String ciCode = "";

    entity.setDescription(request.getParameter("description"));

    if (StringUtils.isNotEmpty(tciId)) {

      ciId = tciId.split(",")[0];
      ciCode = tciId.split(",")[1];

    } else if (StringUtils.isNotEmpty(otherCI)) {
      ConfCiService confCiervice = ContextHolder.getSpringBean("confCiService");
      ConfCi tCi = confCiervice.findOne(otherCI);
      if (tCi != null) {
        ciId = tCi.getId();
        ciCode = tCi.getCode();
      } else {
        entity.setDescription(request.getParameter("description") + "【设备编号:"
            + otherCI + "】");
      }
    }
    String linkManPhone = mobile + "/" + mobileShort + "/" + tel;
    String linkMan = cusUser.getFullname();
    entity.setLinkmanName(linkMan);
    entity.setLinkmanPhone(linkManPhone);
    entity.setCiId(ciId);
    entity.setCiCode(ciCode);

    AppDictService appDictService = ContextHolder
        .getSpringBean(AppDictService.class);

    entity.setId(StringUtils.isEmpty(id) ? HibernateUUIDGenerator.generate()
        : id);
    entity.setSource("微信");
    if(StringUtils.isEmpty(incidentType))
      incidentType="故障";
    entity.setIncidentType(incidentType);
    entity.setTitle(request.getParameter("title"));

    entity.setStatus(appDictService.getInitStatus("INCIDENT_STATUS"));
    entity.setCreator(cusUser.getUsername());
    entity.setCreatorName(cusUser.getFullname());
    entity.setCreateDate(new Timestamp(new Date().getTime()));

    entity.setCusUserId(cusUserId);

    
    icdIncidentService.saveOrUpdate(entity);

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean(BpmProcessRunService.class);

    String starter = cusUser.getUsername();
    if (StringUtils.isEmpty(starter)) {
      starter = "admin";
    }

    bpmProcessRunService.startProcess(starter, "incidentProcess", id, null);

    return "redirect:myIncident";

  }

  @RequestMapping("myIncident")
  public ModelAndView myIncident(String openid, String success,
      String cusUserId, HttpServletRequest request, String type,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView("api/wechat/incident/myIncident");
    if (StringUtils.isEmpty(openid)) {
      return null;
    }
    if (StringUtils.isNotEmpty(type)) {
      mv.addObject("type", type);
    }else
    {
      mv.addObject("type", "1");
      type="1";
    }
    mv.addObject("openid", openid);
    mv.addObject("action", success);
    List<IcdIncident> incidentList=this.getMyIncident(request, null, cusUserId, openid, type);
    mv.addObject("incidents", incidentList);
    return mv;
  }
  


  @RequestMapping("getToCloseIcdCount")
  @ResponseBody
  public long getToCloseIcdCount(HttpServletRequest request,
      HttpServletResponse rps, String cusUserId, String openid) {
    JqGridRequest req = new JqGridRequest();
    long result = 0;
    if (StringUtils.isEmpty(cusUserId)) {
      AppUserService appUserService = ContextHolder
          .getSpringBean(AppUserService.class);

      AppUser cusUser = appUserService.findByOpenid(openid, "id", "name");
      if (cusUser != null) {
        cusUserId = cusUser.getId();
      }
    }
    req.setSelectColumns("id");
    req.addFilterRule("title", JqGridFilterRuleOp.ne, "");
    req.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, cusUserId);

    req.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull, null);
    if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
      req.setSearchString("  (  are_feedback=0 AND (trunc(sysdate)-trunc(create_date))<=30 )");
    } else {
      req.setSearchString("  (  are_feedback=0 AND (datediff(now(),create_date))<=30 )");
    }
    req.setSort("create_date", Direction.DESC);

    List<IcdIncident> response = icdIncidentService.findAll(req).getContent();
    if (response.size() > 0)
      result = response.size();
    return result;
  }

  @RequestMapping("getMyIncident")
  @ResponseBody
  public List<IcdIncident> getMyIncident(HttpServletRequest request,
      HttpServletResponse rps, String cusUserId, String openid, String type) {
    JqGridRequest req = new JqGridRequest();
    req.isPageable(false);

    req.setSelectColumns("id", "code", "title", "create_date", "status");
    if (StringUtils.isEmpty(cusUserId)) {
      AppUserService appUserService = ContextHolder
          .getSpringBean(AppUserService.class);

      AppUser cusUser = appUserService.findByOpenid(openid, "id", "name");
      if (cusUser != null) {
        cusUserId = cusUser.getId();
      }
    }
    req.addFilterRule("title", JqGridFilterRuleOp.ne, "");
    req.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, cusUserId);
    if (type != null && type.equals("1")) {
      req.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnull, null);
    } else if (type != null && type.equals("2")) {
      req.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull,
          null);
      if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
        req.setSearchString("  (  are_feedback=0 AND (trunc(sysdate)-trunc(create_date))<=30 )");
      } else {
        req.setSearchString("  (  are_feedback=0 AND (datediff(now(),create_date))<=30 )");
      }
    } else {
      req.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull,
          null);
      req.setSearchString("  (  are_feedback=1)");
    }

    req.setSort("create_date", Direction.DESC);

    DataResponse<IcdIncident> response = icdIncidentService.findAll(req);
    return response;
  }

  /**
   * 历史工单查看
   * 
   * @param openid
   * @param action
   * @param request
   * @return
   */
  @RequestMapping("myIncidentClosed")
  public ModelAndView myIncidentClosed(String openid, String action,
      HttpServletRequest request) {

    if (StringUtils.isEmpty(openid)) {

    }
    if (StringUtils.isEmpty(action)) {
      action = "1";
    }

    ModelAndView mv = new ModelAndView("api/wechat/incident/myIncidentClosed");
    IcdIncidentService icdIncidentService = ContextHolder
        .getSpringBean(IcdIncidentService.class);

    String cusUserId = "";
    AppUserService appUserService = ContextHolder
        .getSpringBean(AppUserService.class);

    AppUser cusUser = appUserService.findByOpenid(openid, "id", "name");
    if (cusUser != null) {
      cusUserId = cusUser.getId();
    }

    String tabs = request.getParameter("tabs");
    if ("2".equals(tabs)) {

      String page = request.getParameter("page");
      int pageNo = StringUtils.isEmpty(page) ? 1 : Integer
          .parseInt(page.trim());
      JqGridRequest req2 = new JqGridRequest();
      req2.setSelectColumns("id", "code", "title", "are_feedback",
          "satisfaction", "create_date", "status");

      req2.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, cusUserId);
      req2.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull,
          null);

      if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {

        req2.setSearchString("  (are_feedback=1 OR (are_feedback=0 AND (trunc(sysdate)-trunc(create_date))>30) )");
      } else {
        req2.setSearchString("  (are_feedback=1 OR (are_feedback=0 AND (datediff(now(),create_date))>30) )");

      }
      req2.setRows(5);
      req2.setPage(pageNo);
      req2.setPageable(true);
      DataResponse<Map<String, Object>> list2 = icdIncidentService
          .findAllDetailByRequest(req2);

      mv.addObject(
          "pager",
          RenderPager.renderHtml(
              request,
              pageNo,
              5,
              list2.getTotalElements(),
              0,
              "ui-btn ui-shadow ui-corner-all ui-btn-inline ui-mini ui-icon-arrow-l ui-btn-icon-left",
              "ui-btn ui-shadow ui-corner-all ui-btn-inline ui-mini ui-icon-arrow-r ui-btn-icon-right"));

      mv.addObject("incidentsFinish", list2.getContent());

      mv.addObject("tab2", "ui-state-active");
    } else {

      JqGridRequest req = new JqGridRequest();
      req.isPageable(false);
      req.setSelectColumns("id", "code", "title", "are_feedback",
          "satisfaction", "create_date", "status");
      req.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, cusUserId);

      req.addFilterRule("solver_submit_time", JqGridFilterRuleOp.isnotnull,
          null);
      if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
        req.setSearchString("  (  are_feedback=0 AND (trunc(sysdate)-trunc(create_date))<=30 )");
      } else {
        req.setSearchString("  (  are_feedback=0 AND (datediff(now(),create_date))<=30 )");
      }

      List<Map<String, Object>> list1 = icdIncidentService
          .findAllDetailByRequest(req);
      mv.addObject("incidents", list1);
      mv.addObject("tab1", "ui-state-active");
    }

    mv.addObject("openid", openid);
    mv.addObject("action", action);
    mv.addObject("tabs", tabs);

    return mv;
  }

  /**
   * 故障信息
   * 
   * @param id
   * @return
   */
  @RequestMapping("incidentInfo")
  public ModelAndView incidentInfo(String id) {
    ModelAndView mv = new ModelAndView("api/wechat/incident/incidentInfo");
    setIncidentInfoModelAndView(mv, id);
    AppUploadFileService appFileUploadService=ContextHolder
        .getSpringBean("appUploadFileService");
    List<AppUploadFile> list=appFileUploadService.getBySourceId(id).getContent();
    if(list.size()>0)
    {
      mv.addObject("fileList", list);
    }
    
    return mv;
  }

  private void setIncidentInfoModelAndView(ModelAndView mv, String id) {

    IcdIncident entity = icdIncidentService.findOne(id);

    String descStep1 = "登记于" + DateUtils.formatDateTime(entity.getCreateDate())
        + "。";

    String unfinishClass = "list-unfinish";

    String step2 = null, step3 = null, step4 = null, step5 = null, step6 = null, descStep2 = null, descStep3 = null, descStep4 = null, descStep5 = null, descStep6 = null;

    step2 = step3 = step4 = step5 = step6 = unfinishClass;
    AppUserService appUserService = ContextHolder
        .getSpringBean(AppUserService.class);
    if (entity.getAssignDate() != null
        && StringUtils.isNotEmpty(entity.getSupporterId())) {
      step2 = "";
      AppUser supporter = appUserService
          .findByUsername(entity.getSupporterId());
      String slmDesc = "";
      
      if(supporter!=null)
      {
        if (StringUtils.isNotEmpty(entity.getSlmId())) {

          SlmServiceTargetService slmServiceTargetService = ContextHolder
              .getSpringBean(SlmServiceTargetService.class);

          List<Map<String, Object>> slmList = slmServiceTargetService
              .findSlmServiceTargetsValue(entity.getSlmId(), entity.getId());

          for (Map<String, Object> m : slmList) {
            slmDesc += "[" + m.get("target_name") + ":" + m.get("plan_value")
                + "]  ";
          }
        }

        descStep2 = "您的事件单于" + DateUtils.formatDateTime(entity.getAssignDate())
            + "分派至工程师    " + supporter.getFullname() + "(电话："
            + supporter.getMobile() + ")。" + slmDesc;
      }


      step3 = step4 = step5 = step6 = unfinishClass;
    }

    if (entity.getResponseDate() != null) {
      step2 = "";
      step3 = "";
      AppUser responser = appUserService
          .findByUsername(entity.getResponserId());
      if(responser!=null)
      {
        descStep3 = "工程师    "
            + (responser == null ? "" : responser.getFullname() + "(电话："
                + responser.getMobile() + ")") + " 于"
            + DateUtils.formatDateTime(entity.getResponseDate()) + "响应了您的问题。";
      }
      

    }

    if (entity.getArrivalDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      AppUser arriver = appUserService.findByUsername(entity.getArriverId());
      if(arriver!=null)
      {
        descStep4 = "工程师    "
            + (arriver == null ? "" : arriver.getFullname() + "(电话："
                + arriver.getMobile() + ")") + " 于"
            + DateUtils.formatDateTime(entity.getArrivalDate()) + "到达事件现场。";
      }
      

    }

    if (entity.getSolverSubmitTime() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      AppUser solver = appUserService.findByUsername(entity.getSolverId());

      descStep5 = "工程师    "
          + (solver == null ? "" : solver.getFullname() + "(电话："
              + solver.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getSolverSubmitTime()) + "解决了此问题。";

    }

    if (entity.getClosedDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      step6 = "";

      descStep6 = "事件单关闭于" + DateUtils.formatDateTime(entity.getClosedDate())
          + "。";
    }

    mv.addObject("step2", step2);
    mv.addObject("step3", step3);
    mv.addObject("step4", step4);
    mv.addObject("step5", step5);
    mv.addObject("step6", step6);

    mv.addObject("descStep1", descStep1);
    mv.addObject("descStep2", descStep2);
    mv.addObject("descStep3", descStep3);
    mv.addObject("descStep4", descStep4);
    mv.addObject("descStep5", descStep5);
    mv.addObject("descStep6", descStep6);

    mv.addObject("model", entity);
  }

  // 对于企业号，这里的openid 其实是用户账号
  @RequestMapping("userSatisfaction")
  public ModelAndView userSatisfaction(String openid, String id) {
    ModelAndView mv = new ModelAndView("api/wechat/incident/userSatisfaction");

    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");

    List<AppDict> satisfications = appDictService
        .findByType("INCIDENT_SATISFICATION");

    mv.addObject("satisfications", satisfications);
    mv.addObject("id", id);
    mv.addObject("openid", openid);
    mv.addObject("contextUrl", ContextHolder.getWebServerName());
    setIncidentInfoModelAndView(mv, id);
    IcdIncident model = (IcdIncident) mv.getModel().get("model");

    if (model.isAreFeedback()) {
      mv.setViewName("api/wechat/incident/incidentInfo");

    }

    if (model.getSatisfaction() < 1)
      model.setSatisfaction(4);

    return mv;
  }

  @RequestMapping("saveSatisfaction")
  public ModelAndView saveSatisfaction(String openid, IcdIncident model,
      HttpServletRequest request, RedirectAttributes redirectAttributes)
      throws SQLException {

    ModelAndView mv = new ModelAndView();
    model.setCloseCode("客户关闭");
    icdIncidentService.saveSatisfaction(model);
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    
    IcdIncident entity=icdIncidentService.findOne(model.getId());
    if(entity.getProcessId()!=null)
    {
      try {
        bpmProcessRunService.endProcess(openid, entity.getProcessId(),
            model.getCustomerOpinion());
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    mv.setViewName("redirect:myIncident?openid="+openid+"&type=3");
    
    return mv;
  }
  
  @RequestMapping("index2")
  public ModelAndView index2(String openid,
      HttpServletRequest request, RedirectAttributes redirectAttributes)
      throws SQLException {

    ModelAndView mv = new ModelAndView();
    mv.addObject("openid", openid);
    return mv;
  }

  @RequestMapping("uploadFile")
  @ResponseBody
  public void uploadFile(HttpServletRequest request, HttpServletResponse rps)
      throws SQLException, IOException {
    String sourceId = request.getParameter("sourceId");
    String fileName = request.getParameter("fileName");
    String imgCode = request.getParameter("imgCode");
    String openId = request.getParameter("openId");
    String fileSize = request.getParameter("size");

    String ext = "";
    if (fileName.indexOf(".") > 0) {
      ext = fileName.split("\\.")[1];
    }

    String base64Code = imgCode.split(",")[1];

    InputStream inputStr = ImageUtils.BaseToInputStream(base64Code);

    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");

    UploadInfo uploadInfo = ContextHolder.getSpringBean("isperp.uploadInfo");
    UploadFileService<UploadInfo> uploadFileService = ContextHolder
        .getSpringBean("appUploadFileService");

    AppUser us = appUserService.findByOpenid(openId, "fullname", "name");

    uploadInfo.setId(HibernateUUIDGenerator.generate());
    uploadInfo.setSourceId(sourceId);
    uploadInfo.setExt(ext);
    FileUploadUtils.persist(inputStr, uploadInfo);

    if (StringUtils.isNotEmpty(sourceId)) {
      uploadInfo.setModifyDate(new Timestamp(new Date().getTime()));
      uploadInfo.setModifier(us.getName());
      uploadInfo.setCreator(us.getName());
      uploadInfo.setName(fileName);
      uploadInfo.setContentType("image/jpeg");
      uploadInfo.setCreatorName(us.getFullname());
      uploadInfo.setSize(Long.parseLong(fileSize));
      uploadInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
      uploadFileService.saveOrUpdate(uploadInfo);
    }
  }

  @RequestMapping("search")
  public ModelAndView search(String keyword,String time) {

    ModelAndView mv = new ModelAndView("api/wechat/incident/search");

    mv.addObject("keyword", keyword);
    Pageable pg = new PageRequest(1, 200);
    JqGridRequest request = new JqGridRequest(pg);
    request.setSort("create_date",Direction.DESC);
    
    if (StringUtils.isEmpty(keyword)) {
      
      Page<Map<String, Object>> r = this.icdIncidentService
          .findIncidentDetails(request);
      mv.addObject("result", r);
    }else{
    	request.setSearchString(" title like '%"+keyword+"%' or description like '%"+keyword+"%' or incident_type like '%"+keyword+"%' or project_name like '%"+keyword+"%' or create_date like '"+time+"%' ");
    	Page<Map<String, Object>> r = this.icdIncidentService
    	          .findIncidentDetails(request);
    	mv.addObject("result", r);
    }
    
    return mv;
  }
  
  
}
